{% extends "base.html" %}

{% block title %}文档上传 - MinerU 文档解析系统{% endblock %}

{% block page_title %}文档上传{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 上传区域 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">上传文档</h3>
        
        <div id="uploadArea" class="upload-area">
            <div class="space-y-4">
                <div>
                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400"></i>
                </div>
                <div>
                    <p class="text-lg text-gray-600">拖拽文件到这里或点击上传</p>
                    <p class="text-sm text-gray-500">支持 PDF、Word、Excel、PPT 格式，最大 50MB</p>
                </div>
                <div>
                    <input type="file" id="fileInput" class="hidden" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx" multiple>
                    <button id="uploadBtn" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                        <i class="fas fa-plus mr-2"></i>选择文件
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 解析选项 -->
        <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">解析模式</label>
                <select id="parseMode" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="sync" selected>同步解析</option>
                    <option value="async">异步解析</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">输出格式</label>
                <select id="outputFormat" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="markdown">Markdown</option>
                    <option value="text">纯文本</option>
                    <option value="json">JSON</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    任务优先级
                    <span class="text-gray-500 font-normal">(1=最高, 9=最低)</span>
                </label>
                <select id="priority" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="1">1 - 最高优先级</option>
                    <option value="2">2 - 很高优先级</option>
                    <option value="3">3 - 高优先级</option>
                    <option value="4">4 - 较高优先级</option>
                    <option value="5" selected>5 - 普通优先级</option>
                    <option value="6">6 - 较低优先级</option>
                    <option value="7">7 - 低优先级</option>
                    <option value="8">8 - 很低优先级</option>
                    <option value="9">9 - 最低优先级</option>
                </select>
            </div>
        </div>
        
        <!-- 进度条 -->
        <div id="progressContainer" class="mt-6 hidden">
            <div class="flex justify-between items-center mb-2">
                <span class="text-sm text-gray-600">上传进度</span>
                <span id="progressText" class="text-sm text-gray-800">0%</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2">
                <div id="progressBar" class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
            </div>
        </div>
    </div>
    
    <!-- 文件列表 -->
    <div class="bg-white rounded-xl shadow-sm p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">文件列表</h3>
        
        <div id="fileList" class="space-y-2">
            <div class="text-center py-8 text-gray-500">
                <i class="fas fa-folder-open text-3xl mb-2"></i>
                <p>暂无文件</p>
            </div>
        </div>
        
        <div class="mt-4 flex justify-end">
            <button id="startUploadBtn" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <i class="fas fa-upload mr-2"></i>开始上传
            </button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let selectedFiles = [];

// 文件选择
document.getElementById('uploadBtn').addEventListener('click', function() {
    document.getElementById('fileInput').click();
});

document.getElementById('fileInput').addEventListener('change', function(e) {
    handleFiles(e.target.files);
});

// 拖拽上传
const uploadArea = document.getElementById('uploadArea');
uploadArea.addEventListener('dragover', function(e) {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', function(e) {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', function(e) {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    handleFiles(e.dataTransfer.files);
});

// 处理文件
function handleFiles(files) {
    Array.from(files).forEach(file => {
        if (selectedFiles.length >= 10) {
            showNotification('最多只能上传10个文件', 'error');
            return;
        }
        
        if (file.size > 50 * 1024 * 1024) {
            showNotification(`文件 ${file.name} 超过50MB限制`, 'error');
            return;
        }
        
        const allowedTypes = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'];
        const fileExt = '.' + file.name.split('.').pop().toLowerCase();
        if (!allowedTypes.includes(fileExt)) {
            showNotification(`文件 ${file.name} 格式不支持`, 'error');
            return;
        }
        
        selectedFiles.push(file);
        updateFileList();
    });
}

// 更新文件列表
function updateFileList() {
    const fileList = document.getElementById('fileList');
    const startUploadBtn = document.getElementById('startUploadBtn');
    
    if (selectedFiles.length === 0) {
        fileList.innerHTML = `
            <div class="text-center py-8 text-gray-500">
                <i class="fas fa-folder-open text-3xl mb-2"></i>
                <p>暂无文件</p>
            </div>
        `;
        startUploadBtn.disabled = true;
    } else {
        fileList.innerHTML = selectedFiles.map((file, index) => `
            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-file text-blue-600"></i>
                    <div>
                        <p class="text-sm font-medium text-gray-800">${file.name}</p>
                        <p class="text-xs text-gray-500">${formatFileSize(file.size)}</p>
                    </div>
                </div>
                <button onclick="removeFile(${index})" class="text-red-500 hover:text-red-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `).join('');
        startUploadBtn.disabled = false;
    }
}

// 移除文件
function removeFile(index) {
    selectedFiles.splice(index, 1);
    updateFileList();
}

// 开始上传
document.getElementById('startUploadBtn').addEventListener('click', async function() {
    if (selectedFiles.length === 0) {
        showNotification('请先选择文件', 'error');
        return;
    }
    
    const parseMode = document.getElementById('parseMode').value;
    const outputFormat = document.getElementById('outputFormat').value;
    const priority = document.getElementById('priority').value;
    
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    
    progressContainer.classList.remove('hidden');
    this.disabled = true;
    
    try {
        const formData = new FormData();
        selectedFiles.forEach(file => {
            formData.append('files', file);
        });
        formData.append('parse_mode', parseMode);
        formData.append('output_format', outputFormat);
        formData.append('priority', priority);
        
        const token = new URLSearchParams(window.location.search).get('token');
        
        // 验证token是否存在
        if (!token) {
            showNotification('登录已过期，请重新登录', 'error');
            setTimeout(() => {
                window.location.href = '/web/login';
            }, 2000);
            return;
        }
        
        // 使用XMLHttpRequest来跟踪上传进度
        const xhr = new XMLHttpRequest();
        
        // 监听上传进度
        xhr.upload.addEventListener('progress', function(e) {
            if (e.lengthComputable) {
                const percentComplete = (e.loaded / e.total) * 100;
                progressBar.style.width = percentComplete + '%';
                progressText.textContent = Math.round(percentComplete) + '%';
            }
        });
        
        // 监听请求完成
        xhr.addEventListener('load', function() {
            if (xhr.status === 200) {
                try {
                    const result = JSON.parse(xhr.responseText);
                    showNotification(`上传成功！创建了 ${result.task_ids.length} 个任务`, 'success');
                    
                    // 清空文件列表
                    selectedFiles = [];
                    updateFileList();
                    
                    // 重置进度条
                    progressBar.style.width = '0%';
                    progressText.textContent = '0%';
                    progressContainer.classList.add('hidden');
                    document.getElementById('startUploadBtn').disabled = false;
                    
                    // 跳转到任务页面
                    setTimeout(() => {
                        window.location.href = `/web/tasks?token=${token}`;
                    }, 1000);
                } catch (e) {
                    showNotification('解析响应失败', 'error');
                    document.getElementById('startUploadBtn').disabled = false;
                }
            } else {
                handleUploadError(xhr);
            }
        });
        
        // 监听网络错误
        xhr.addEventListener('error', function() {
            showNotification('网络错误，请检查连接', 'error');
            document.getElementById('startUploadBtn').disabled = false;
        });
        
        // 监听请求超时
        xhr.addEventListener('timeout', function() {
            showNotification('请求超时，请重试', 'error');
            document.getElementById('startUploadBtn').disabled = false;
        });
        
        // 发送请求
        xhr.open('POST', '/api/v1/parse/upload', true);
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
        xhr.timeout = 300000; // 5分钟超时
        xhr.send(formData);
        
        // 处理上传错误的函数
        function handleUploadError(xhr) {
            try {
                const error = JSON.parse(xhr.responseText);
                
                // 处理认证错误
                if (xhr.status === 401) {
                    showNotification('登录已过期，请重新登录', 'error');
                    setTimeout(() => {
                        window.location.href = '/web/login';
                    }, 2000);
                } else {
                    showNotification(error.detail || '上传失败', 'error');
                }
            } catch (e) {
                showNotification('上传失败，请稍后重试', 'error');
            }
            document.getElementById('startUploadBtn').disabled = false;
        }
    } catch (error) {
        console.error('上传失败:', error);
        showNotification('上传失败，请稍后重试', 'error');
        this.disabled = false;
    }
});
</script>
{% endblock %}